package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.pro.domain.entity.StockDateFilterEntity;
import com.xbongbong.pro.product.pojo.dto.StockDateSaveFilterDTO;
import com.xbongbong.saas.model.StockDateFilterModel;
import com.xbongbong.saas.service.StockDateFilterService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("stockDateFilterService")
public class StockDateFilterServiceImpl implements StockDateFilterService {

    @Resource
    private StockDateFilterModel stockDateFilterModel;

    @Override
    public BaseVO saveStockDateFilter(StockDateSaveFilterDTO stockDateSaveFilterDTO) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", stockDateSaveFilterDTO.getCorpid());
        param.put("userId", stockDateSaveFilterDTO.getUserId());
        param.put("formId", stockDateSaveFilterDTO.getFormId());
        param.put("businessType", stockDateSaveFilterDTO.getBusinessType());
        param.put("del", DelEnum.NORMAL.getDel());
        List<StockDateFilterEntity> stockDateFilterEntityList = stockDateFilterModel.findEntitys(param);
        if (stockDateFilterEntityList.isEmpty()) {
            StockDateFilterEntity stockDateFilterEntity = new StockDateFilterEntity(stockDateSaveFilterDTO.getCorpid(), stockDateSaveFilterDTO.getFormId(), stockDateSaveFilterDTO.getUserId(), stockDateSaveFilterDTO.getBusinessType());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("timeName", stockDateSaveFilterDTO.getTimeName());
            jsonObject.put("timeType", stockDateSaveFilterDTO.getTimeType());
            jsonObject.put("startTime", stockDateSaveFilterDTO.getStartTime());
            jsonObject.put("endTime", stockDateSaveFilterDTO.getEndTime());
            stockDateFilterEntity.setContentData(jsonObject);
            stockDateFilterModel.save(stockDateFilterEntity);
        } else {
            StockDateFilterEntity stockDateFilterEntity = stockDateFilterEntityList.get(0);
            JSONObject jsonObject = stockDateFilterEntity.getContentData() == null ? new JSONObject() : stockDateFilterEntity.getContentData();
            jsonObject.put("timeName", stockDateSaveFilterDTO.getTimeName());
            jsonObject.put("timeType", stockDateSaveFilterDTO.getTimeType());
            jsonObject.put("startTime", stockDateSaveFilterDTO.getStartTime());
            jsonObject.put("endTime", stockDateSaveFilterDTO.getEndTime());
            stockDateFilterEntity.setContentData(jsonObject);
            stockDateFilterModel.update(stockDateFilterEntity);
        }
        return null;
    }
}
